<?php


namespace app\api\model\order;


use app\logic\model\OrderOpusModel as OrderOpus;

use app\logic\model\SettingModel;
use app\api\common;
use app\api\model\OpusModel;
use app\api\model\UserModel;
use think\facade\Db;

class OrderOpusModel extends OrderOpus
{
    /**
     * 创建原创作品订单
     * @param $opusId int 作品标识
     * @param $opusNumberIds array 作品编号标识
     */
    function createOrder($opusId,$opusNumberIds,$vip=0){
        global $user;
        $opusModel=new OpusModel();
        $opus=$opusModel->getFindByid($opusId);
        $each_price=$opus['each_price'];//每份金额
        Db::startTrans();
        try {
            /**佣金-开始**/
            $commissionPrice=$this->getCommissionPrice($opus);
            $member_uid=$commissionPrice['member_uid'];
            $member_commission_price=$commissionPrice['member_commission_price'];
            $head_uid=$commissionPrice['head_uid'];
            $head_commission_price=$commissionPrice['head_commission_price'];
            /**佣金-结束**/
            /**平台佣金-开始**///平台佣金=作家服务费比例*作品金额
            $writer=(new UserModel())->getFindByid($opus['writer_id']);
            if(empty($writer)){
                show_json('wxapp.orderOpus.create.no_writer');
            }
            if($writer['writer_rate']==-1){
                $writer['writer_rate']=(new SettingModel())->get_value('writer_rate');
            }
            $platform_price=$each_price*round($writer['writer_rate']/100,2);
            /**平台佣金-结束**/
            /**卖家收益-开始**///卖家收益=作品金额-平台佣金-团员佣金金额-团长佣金金额
            $seller_price=$each_price-$platform_price-$member_commission_price-$head_commission_price;
            /**卖家收益-结束**/
            /**创建主表-开始**/
            $countOpusNumberNum=count($opusNumberIds);
            $orderCreateData=array(
                'buyer_id'=>$user['id'],
                "ordersn"=>common::getOrdersn('OQ',rand(10000,99999)),
                "price"=>$countOpusNumberNum*$each_price,//总金额
                "status"=>0,//支付状态为0
                'seller_id'=>$opus['writer_id'],
                'is_commission'=>$commissionPrice['is_commission'],
                'member_uid'=>$member_uid,
                'member_commission_price'=>$member_commission_price*$countOpusNumberNum,
                'head_uid'=>$head_uid,
                'head_commission_price'=>$head_commission_price*$countOpusNumberNum,
                'write_copyright_price'=>0,
                'create_time'=>time(),
                'seller_price'=>$seller_price*$countOpusNumberNum,
                'premium_price'=>0,
                'opus_id'=>$opusId,
                'platform_price'=>$platform_price*$countOpusNumberNum,
            );
            $order_id=Db::name("order_pay")->insertGetId($orderCreateData);
            /**创建主表-结束**/
            /**创建opusNumber表-开始**/
            $createData=[];
            foreach ($opusNumberIds as $val){
                $createData[]=array(
                    'ordersn'=>common::getOrdersn('OPQ',rand(100,999)),
                    'opus_number_id'=>$val,
                    'opus_id'=>$opusId,
                    'buyer_id'=>$user['id'],
                    'seller_id'=>$opus['writer_id'],//购买原创作品，一定是作家的
                    'status'=>0,
                    'price'=>$each_price,
                    'premium_price'=>0,//购买原创作品，溢价金额一定是0
                    'platform_price'=>$platform_price,//平台佣金
                    'is_commission'=>$commissionPrice['is_commission'],
                    'commission_price'=>$commissionPrice['commission_price'],
                    'member_uid'=>$member_uid,
                    'member_commission_price'=>$member_commission_price,
                    'head_uid'=>$head_uid,
                    'head_commission_price'=>$head_commission_price,
                    'write_copyright_price'=>0,
                    'seller_price'=>$seller_price,
                    'order_pay_id'=>$order_id,
                    'vip'=>$vip
                );
            }
            $this->saveAll($createData);
            /**创建opusNumber表-结束**/
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>-1,'msg'=>$e->getMessage()];
        }
        return ['code'=>0,'order_id'=>$order_id];
    }

    function getCommissionPrice($opus){
        global $user;
        $agent=(new UserModel)->getAgent();
        $return=array(
            'is_commission'=> $opus['is_commission']==1,
            'commission_price'=>0,
            'member_commission_price'=>0,
            'member_uid'=>$agent['member_uid'],
            'head_commission_price'=>0,
            'head_uid'=>$agent['head_uid'],
        );
        if($return['is_commission']){
            if(!empty($return['member_uid'])||!empty($return['head_uid'])) {
                //分销佣金
                $price = round($opus['each_price'] * $opus['commission_rate'] / 100, 2);
                if ($agent['member_uid']) {
                    $head_user = (new UserModel)->getFindByid($agent['head_uid']);
                    //获取团长佣金开始
                    $head_price = round($price * $head_user['head_commission_rate'] / 100, 2);
                    //团长佣金
                    $return['head_commission_price'] = $head_price;
                    //团员佣金
                    $return['member_commission_price'] = $price - $head_price;
                } else {
                    $return['head_commission_price'] = $price;
                }
                $return['price'] = $price;
            }
        }
        return $return;
    }

    function getList($param,$field="*",$limit,$isPage=true){
        $list=$this->where(function($q) use ($param){
            if(check_request($param,'order_pay_id')){
                $q->where('order_pay_id',$param['order_pay_id']);
            }
        })->field($field);
        if($isPage){
            $list=$list->paginate($limit);
        }else{
            $list=$list->limit($limit)->select();
        }
        if(!$list->isEmpty()){
            return $list->toArray();
        }
        return $list;
    }
    function updateOrder($id,$data){
        return $this->where('id',$id)->save($data);
    }
}